package library_system.com;

import library_system.Util.DBUtil;
import library_system.model.Book;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author haomin
 * @date 2022/04/07 08:25
 **/
public class PutAwayCommandV2 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        Book book = new Book();

        System.out.print("请输入您要上架的书籍名称：");
        book.name = scanner.nextLine();
        System.out.print("请输入您上架的数目：");
        book.stock = scanner.nextInt();

        try(Connection c = DBUtil.connection()){
            String sql = "select bid from books where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)){
                ps.setString(1,book.name);

                try(ResultSet rs = ps.executeQuery()){
                    if(rs.next()){
                        book.bid = rs.getInt("bid");
                    }
                }
            }
        }

        if(book.bid == null){
            // 进行 insert
            try(Connection c = DBUtil.connection()){
                String sql = "insert into books (name, stock ,total) values (?,?,?)";
                try(PreparedStatement ps = c.prepareStatement(sql)){
                    ps.setString(1,book.name);
                    ps.setInt(2,book.stock);
                    ps.setInt(3,book.stock);

                    ps.executeUpdate();
                }
            }
        }else {
            // 进行 update
            try(Connection c = DBUtil.connection()){
                String sql = "update books set stock = stock + ?,total = total + ? where bid = ?";
                try(PreparedStatement ps = c.prepareStatement(sql)){
                    ps.setInt(1,book.stock);
                    ps.setInt(2,book.stock);
                    ps.setInt(3,book.bid);

                    ps.executeUpdate();
                }
            }
        }
        System.out.println("上架成功");
    }
}